from django.shortcuts import render,HttpResponse
from django.http import JsonResponse

# 额外增加路径
import sys
sys.path.append('/home/server_try/app01')

#防止403和500,每个函数前面都得加
from django.views.decorators.csrf import csrf_exempt

from helpers import *
from connect import *

#数据库的连接
db=get_db()
cursor = db.cursor()

# Create your views here.
@csrf_exempt
def index(request):
	return HttpResponse("welcome body")

@csrf_exempt
def login(request):

    res=HttpResponse()
    
    user_name=str(request.POST['studentname'])
    user_pwd=str(request.POST['password'])

    #检查是否有同名的用户
    if userCheckSameName(cursor,user_name):
        #检查密码是否正确
        res['user_id']=userCheckPwd(cursor,user_name,user_pwd)
    else:
        #如果不存在该用户，则新增用户
        res['user_id']=user_add(cursor,user_name,user_pwd)
    
    show_user(cursor)
    
    if res['user_id']!="":
        res['sign']='success'
    else:
        res['sign']='failure'

    db.commit()
    return res

    #课程所需的界面
@csrf_exempt
def CourseData(request):
    res={}
    
    pageSort=request.POST['pageSort']
    print(pageSort)
    
    titles = getTitles(cursor,pageSort)

    courses=[]
    res['titles']=titles
    
    # 通过课程类别获取课程
    for title in titles:
        courses.append(getCourses(cursor,title))
    
    res['courses']=courses
    
    return JsonResponse(res)
